<template>
  <div class="permission-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="资源">
          <el-input v-model="searchForm.resource" placeholder="请输入资源" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="菜单" value="MENU" />
            <el-option label="按钮" value="BUTTON" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
          <el-button type="success" @click="refreshData" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="action-card">
      <el-button 
        v-if="hasPermission('system:permission:create')"
        type="primary" 
        @click="showCreateDialog"
        icon="Plus"
      >
        新增权限
      </el-button>
      <el-button @click="expandAll" icon="Expand">展开全部</el-button>
      <el-button @click="collapseAll" icon="Fold">收起全部</el-button>
    </el-card>

    <!-- 权限树表格 -->
    <el-card>
      <el-table
        ref="tableRef"
        :data="permissionTree"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
      >
        <el-table-column prop="name" label="权限名称" min-width="200" />
        <el-table-column prop="resource" label="资源" width="150" />
        <el-table-column prop="action" label="操作" width="100" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === 'MENU' ? 'primary' : 'success'">
              {{ row.type === 'MENU' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="150" />
        <el-table-column prop="visible" label="可见" width="80">
          <template #default="{ row }">
            <el-tag :type="row.visible ? 'success' : 'danger'">
              {{ row.visible ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="hasPermission('system:permission:create')"
              type="success" 
              size="small" 
              icon="Plus"
              @click="addChild(row)"
            >
              添加子权限
            </el-button>
            <el-button 
              v-if="hasPermission('system:permission:edit')"
              type="primary" 
              size="small" 
              icon="Edit"
              @click="editPermission(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="hasPermission('system:permission:delete')"
              type="danger" 
              size="small" 
              icon="Delete"
              @click="deletePermission(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePermission } from '@/composables/usePermission'
import api from '@/utils/request'

const { hasPermission } = usePermission()

const loading = ref(false)
const permissionTree = ref([])
const tableRef = ref()

const searchForm = ref({
  name: '',
  resource: '',
  type: ''
})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await api.get('/permissions/tree')
    permissionTree.value = response.data || []
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 对树数据进行过滤
  fetchData()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    resource: '',
    type: ''
  }
  fetchData()
}

const refreshData = () => {
  fetchData()
}

const expandAll = () => {
  // 展开所有节点
  const expandAllNodes = (data: any[]) => {
    data.forEach(item => {
      tableRef.value?.toggleRowExpansion(item, true)
      if (item.children && item.children.length > 0) {
        expandAllNodes(item.children)
      }
    })
  }
  expandAllNodes(permissionTree.value)
}

const collapseAll = () => {
  // 收起所有节点
  const collapseAllNodes = (data: any[]) => {
    data.forEach(item => {
      tableRef.value?.toggleRowExpansion(item, false)
      if (item.children && item.children.length > 0) {
        collapseAllNodes(item.children)
      }
    })
  }
  collapseAllNodes(permissionTree.value)
}

const showCreateDialog = () => {
  ElMessage.info('创建权限功能待实现')
}

const addChild = (parent: any) => {
  ElMessage.info(`为 ${parent.name} 添加子权限功能待实现`)
}

const editPermission = (permission: any) => {
  ElMessage.info('编辑权限功能待实现')
}

const deletePermission = async (permission: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除权限 ${permission.name} 吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.delete(`/permissions/${permission.id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.search-card, .action-card {
  margin-bottom: 20px;
}
</style>

